package com.wbp.cms.core.project.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Preconditions;
import com.wbp.cms.client.common.domain.DictionaryDO;
import com.wbp.cms.client.common.service.DictionaryService;
import com.wbp.cms.client.constant.CommonConstant;
import com.wbp.cms.client.product.domain.ProductDO;
import com.wbp.cms.client.project.domain.ContractDO;
import com.wbp.cms.client.project.domain.ProjectDO;
import com.wbp.cms.client.project.domain.ProjectProfitDO;
import com.wbp.cms.client.project.domain.ProjectWorkOrderDO;
import com.wbp.cms.client.project.query.ProjectQuery;
import com.wbp.cms.client.project.service.ContractService;
import com.wbp.cms.client.project.service.ProjectProfitService;
import com.wbp.cms.client.project.service.ProjectService;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.core.exception.ServiceException;
import com.wbp.cms.core.product.dao.ProductDAO;
import com.wbp.cms.core.project.dao.ProjectDAO;
import com.wbp.cms.core.project.dao.ProjectWorkOrderDAO;


/**
 * @Description:
 * @Department:
 * @author andy.lhc
 * @date 2016年3月9日 下午3:09:48
 */
@Service("projectService")
public class ProjectServiceImpl implements ProjectService {
  
  /**
   * 
   */
  private static final long serialVersionUID = -8249951827137768682L;

  private static final Logger logger = Logger.getLogger(ProjectServiceImpl.class) ;
  
  @Resource
  private  ProjectDAO  projectDAO ;
  
  @Resource
  private ContractService  contractService ;
  
  @Resource
  private ProjectProfitService  projectProfitService ;
  
  //@Resource
  //private ProjectWorkOrderSerivce  projectWorkOrderSerivce ;
  
  @Resource
  private ProjectWorkOrderDAO  projectWorkOrderDAO ;
  
  @Resource
  private DictionaryService  dictionaryService ;
  
  @Resource
  private ProductDAO  productDAO ;

  @Override
  @Transactional
  public Result<Long> addProject(ProjectDO projectDO) {
    logger.error("projectDO:"+projectDO );
    Preconditions.checkNotNull(projectDO, "projectDO:"+projectDO+",不能为null") ;
    Preconditions.checkArgument(projectDO.getProductId() !=null && projectDO.getProductId() >0, "projectId 不能为空");
    Preconditions.checkArgument(projectDO.getCustomerId() !=null && projectDO.getCustomerId() >0, "customerId 不能为空");
    Preconditions.checkArgument(projectDO.getUserId() !=null && projectDO.getUserId() >0, "userId 不能为空");
    Preconditions.checkArgument(projectDO.getPreAmount()  >0, "PreAmount 应>0");
    Preconditions.checkArgument(projectDO.getType() >0, "Type 应>0");
    Preconditions.checkArgument(projectDO.getReserveType() >0, "ReserveType 应>0");
    
    // 先减库存 
    ProductDO  product = this.productDAO.load(projectDO.getProductId()) ;
    if(product == null)
       return Result.buildError("预约产品已删除，请重新选择") ;
   //  Preconditions.checkArgument(product.getSurplusAmount() >0, "SurplusAmount 应>0");
    if(product.getSurplusAmount()  <=0)
        return Result.buildError("此产品剩余额度已预约完，请重新选择其他产品") ; 
    
    if(product.getSubscribePoint()>0 && projectDO.getPreAmount() < product.getSubscribePoint()){
       return Result.buildError("必须达到预约起点金额:"+product.getSubscribePoint()+"万") ;
    }
    
    if(product.getSurplusAmount() < projectDO.getPreAmount() ){
       return Result.buildError("预约产品剩余额度不足，最多只能预约:"+product.getSurplusAmount()+"万");
    }
    
    // product.setSurplusAmount( product.getSurplusAmount()-projectDO.getPreAmount() );
    product.setPreAmount(projectDO.getPreAmount());
    if( this.productDAO.decStock(product) <=0 )
       return Result.buildError("更新产品:"+product.getId()+"库存失败,请刷新页面重试!");

    Long projectId = this.projectDAO.insert(projectDO) ;
    ContractDO  contract = projectDO.getContract() ;
    if(contract !=null ){
       contract.setProjectId(projectId);
       this.contractService.addContract(contract) ;
    }
    
    /*List<ProjectProfitDO>  projectProfitList = projectDO.getProjectProfitList() ;
    if(projectProfitList !=null && !projectProfitList.isEmpty() ){
        this.projectProfitService.batchAddProjectProfit(projectProfitList, projectId) ;
    }*/
    
    // 创建申请工单
    createProjectWorkerOrder(projectDO) ;
    
    
    return Result.buildSuccess(projectId);
  }

   
  @Override
  @Transactional
  public Result<Boolean> modifyProject(ProjectDO projectDO) {
    logger.error("projectDO:"+projectDO );
    Preconditions.checkNotNull(projectDO, "projectDO:"+projectDO+",不能为null") ;
    Preconditions.checkNotNull(projectDO.getId(), "projectId:"+projectDO.getId()+",不能为null") ;
    Preconditions.checkArgument(projectDO.getId() >0 , "projectId:"+projectDO.getId()+",应>0");
    Preconditions.checkArgument(projectDO.getStatus()>0 , "status:"+projectDO.getStatus()+",应>0");
    
    ProjectDO  oldProject = this.projectDAO.load(projectDO.getId());
    boolean b = this.projectDAO.update(projectDO) > 0 ;
    if(!b)
      throw new ServiceException("修改预约项目失败") ;
    
    ContractDO  contract = projectDO.getContract() ;
    if(contract !=null  && contract.getProjectId() !=null && contract.getProjectId() > 0 ){
      Result<Boolean> cr = this.contractService.modifyContract(contract) ;
      if(cr.isFailed())
         throw  new ServiceException("modifyContract失败") ;
    }
    
    List<ProjectProfitDO>  projectProfitList =null ;
    projectProfitList = this.projectProfitService.queryProjectProfitByProject(projectDO.getId()) ;
    if(projectProfitList !=null && !projectProfitList.isEmpty() ){  // 如果之前已有先删除掉 
       if(! this.projectProfitService.deleteProjectProfitByProject(projectDO.getId()) )
          throw  new ServiceException("modifyProject--deleteProjectProfitByProject失败") ; 
    }
    
    projectProfitList = projectDO.getProjectProfitList() ;
    if(projectProfitList !=null && !projectProfitList.isEmpty() ){ 
      this.projectProfitService.batchAddProjectProfit(projectProfitList, projectDO.getId()) ;  // 新增
    }
    
    
    if(oldProject.getStatus() != projectDO.getStatus() ){
        // 创建申请工单
       createProjectWorkerOrder(projectDO) ;
    }
    
    return Result.buildSuccess(b);
  }
  
  private void  createProjectWorkerOrder(ProjectDO projectDO){
    ProjectWorkOrderDO  pwo = new ProjectWorkOrderDO();
    pwo.setProjectId(projectDO.getId());
    pwo.setName(projectDO.getProjectName());
    pwo.setStatus(projectDO.getStatus());  
    DictionaryDO dd = null ;
    if(projectDO.getReserveType() == CommonConstant.PROJECT_RESERVE_TYPE_1)
       dd = dictionaryService.queryDictionary("Project", CommonConstant.PROJECT_STATUS_1, pwo.getStatus()) ;
    else if( projectDO.getReserveType() == CommonConstant.PROJECT_RESERVE_TYPE_2)
      dd = dictionaryService.queryDictionary("Project", CommonConstant.PROJECT_STATUS_2, pwo.getStatus()) ;
    pwo.setDescription( dd !=null ? dd.getDescription() : "" );
    pwo.setComments(projectDO.getComments());
    if( this.projectWorkOrderDAO.insert(pwo) <=0 ) 
      throw  new ServiceException("新增projectWorkOrderSerivce失败") ;
    
  }

   
  @Override
  public Result<ProjectDO> loadProject(Long projectId) {
    Preconditions.checkNotNull(projectId, "projectId:"+projectId+",不能为null") ;
    Preconditions.checkArgument(projectId > 0 , "projectId:"+projectId+",应该 >0 ") ;
    ProjectDO  project = this.projectDAO.load(projectId) ;
    if(project == null){
      return Result.buildError(BaseResultCode.PROJECT_QUERY_NOT_FUND) ;
    }
    
    project.setContract( this.contractService.loadContractByProject(project.getId()) );
    project.setProjectProfitList( this.projectProfitService.queryProjectProfitByProject(projectId) ) ;
    
   // Result<List<ProjectWorkOrderDO>>  pwoList =projectWorkOrderSerivce.queryProjectWorkOrderByProject(projectId)  ;
 //   project.setProjectWorkOrderList(pwoList.getData() );
    
    return Result.buildSuccess(project);
  }

   
  @Override
  public Result<List<ProjectDO>> queryProject(ProjectQuery projectQuery) {
    Preconditions.checkNotNull(projectQuery, "projectQuery:"+projectQuery+",不能为null") ;
    
    int count = 0 ; 
    List<ProjectDO> list = null ;
    
    try{
         if(projectQuery.getOrganizationId() == null || projectQuery.getOrganizationId() <=0){
            count = this.projectDAO.queryCount(projectQuery) ; 
            if(count >0 ){
              list  = this.projectDAO.query(projectQuery) ;
            }
         }else{
           count = this.projectDAO.queryChildenCount(projectQuery) ; 
           if(count >0 ){
             list  = this.projectDAO.queryChilden(projectQuery) ;
           }
         }
    }catch(Exception e){
      logger.error("queryProject exception:",e);
      return Result.buildError("queryProject查询为空") ;
    }
    
    return Result.buildSuccess(count, list);
  }

}
